package com.sesame.controller;

import kim.sesame.framework.cas.CasUtil;
import kim.sesame.framework.exception.BusinessException;
import kim.sesame.framework.utils.Argument;
import kim.sesame.common.web.controller.AbstractWebController;
import kim.sesame.common.result.ApiResult;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@CommonsLog
@RestController
@RequestMapping("/user")
public class UserController extends AbstractWebController {

    /**
     * 判断是否登录过
     *
     * @param request
     * @return
     */
    @RequestMapping("/verifyLogin")
    public ApiResult verifyLogin(HttpServletRequest request,HttpServletResponse response) {
        String sessionId = CasUtil.getSessionId(request);

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");

        return success(sessionId);
    }
    /**
     * 保存cas 的登录信息
     * @return
     */
    @RequestMapping("/saveCasLogin")
    public ApiResult saveCasLogin(String casId, HttpServletRequest request, HttpServletResponse response) {
        Argument.notEmpty(casId, "casId 不能为空");

        CasUtil.saveSessionIdToCookie(casId, response);

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");

        return success();
    }

    @RequestMapping("/login")
    public ApiResult login(String account, String pwd, HttpServletRequest request, HttpServletResponse response) {
        Argument.notEmpty(account, "account 不能为空");
        Argument.notEmpty(pwd, "pwd 不能为空");

        // 验证用户名密码
        boolean flg = account.equals("admin") && pwd.equals("123456");
        if (!flg) {
            throw new BusinessException("用户名和密码错");
        } else {
            String sessionId = CasUtil.saveSessionIdToCookie(request, response);
            return success(sessionId);
        }

    }


}
